package com.zweirm.lagee_quizing_web.service;

import com.zweirm.lagee_quizing_web.domain.Clazz;
import com.zweirm.lagee_quizing_web.domain.StudentUser;
import com.zweirm.lagee_quizing_web.repository.ClazzRepository;
import com.zweirm.lagee_quizing_web.repository.StudentUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentUserService {
    @Autowired
    private StudentUserRepository studentUserRepository;

    @Autowired
    private ClazzRepository clazzRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public void saveUser(String email, String password, String phone, String clazz, String name) {
        StudentUser studentUser = new StudentUser();
        Clazz destClazz = clazzRepository.findClazzByName(clazz);
        studentUser.setEmail(email);
        studentUser.setPassword(passwordEncoder.encode(password));
        studentUser.setPhone(phone);
        studentUser.setClazz(destClazz);
        studentUser.setName(name);

        List<StudentUser> destStudentUserList = new ArrayList<>();
        destStudentUserList.add(studentUser);
        destClazz.setStudentUsers(destStudentUserList);

        clazzRepository.save(destClazz);
        studentUserRepository.save(studentUser);
    }

    public String findUserByEmail(String email) {
        return studentUserRepository.findByEmail(email);
    }
}
